home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / source / objects / stringobject.c < prev    next >
C/C++ Source or Header  |  1999-06-14  |  25KB  |  1,138 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* String object implementation */
  33.  
  34. #include "Python.h"
  35.  
  36. #include "mymath.h"
  37. #include <ctype.h>
  38.  
  39. #ifdef COUNT_ALLOCS
  40. int null_strings, one_strings;
  41. #endif
  42.  
  43. #ifdef HAVE_LIMITS_H
  44. #include <limits.h>
  45. #else
  46. #ifndef UCHAR_MAX
  47. #define UCHAR_MAX 255
  48. #endif
  49. #endif
  50.  
  51. #include "protos/stringobject.h"
  52.  
  53. static PyStringObject *characters[UCHAR_MAX + 1];
  54. #ifndef DONT_SHARE_SHORT_STRINGS
  55. static PyStringObject *nullstring;
  56. #endif
  57.  
  58. /*
  59.    Newsizedstringobject() and newstringobject() try in certain cases
  60.    to share string objects.  When the size of the string is zero,
  61.    these routines always return a pointer to the same string object;
  62.    when the size is one, they return a pointer to an already existing
  63.    object if the contents of the string is known.  For
  64.    newstringobject() this is always the case, for
  65.    newsizedstringobject() this is the case when the first argument in
  66.    not NULL.
  67.    A common practice to allocate a string and then fill it in or
  68.    change it must be done carefully.  It is only allowed to change the
  69.    contents of the string if the obect was gotten from
  70.    newsizedstringobject() with a NULL first argument, because in the
  71.    future these routines may try to do even more sharing of objects.
  72. */
  73. PyObject *
  74. PyString_FromStringAndSize(str, size)
  75.     const char *str;
  76.     int size;
  77. {
  78.     register PyStringObject *op;
  79. #ifndef DONT_SHARE_SHORT_STRINGS
  80.     if (size == 0 && (op = nullstring) != NULL) {
  81. #ifdef COUNT_ALLOCS
  82.         null_strings++;
  83. #endif
  84.         Py_INCREF(op);
  85.         return (PyObject *)op;
  86.     }
  87.     if (size == 1 && str != NULL &&
  88.         (op = characters[*str & UCHAR_MAX]) != NULL)
  89.     {
  90. #ifdef COUNT_ALLOCS
  91.         one_strings++;
  92. #endif
  93.         Py_INCREF(op);
  94.         return (PyObject *)op;
  95.     }
  96. #endif /* DONT_SHARE_SHORT_STRINGS */
  97.     op = (PyStringObject *)
  98.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  99.     if (op == NULL)
  100.         return PyErr_NoMemory();
  101.     op->ob_type = &PyString_Type;
  102.     op->ob_size = size;
  103. #ifdef CACHE_HASH
  104.     op->ob_shash = -1;
  105. #endif
  106. #ifdef INTERN_STRINGS
  107.     op->ob_sinterned = NULL;
  108. #endif
  109.     _Py_NewReference(op);
  110.     if (str != NULL)
  111.         memcpy(op->ob_sval, str, size);
  112.     op->ob_sval[size] = '\0';
  113. #ifndef DONT_SHARE_SHORT_STRINGS
  114.     if (size == 0) {
  115.         nullstring = op;
  116.         Py_INCREF(op);
  117.     } else if (size == 1 && str != NULL) {
  118.         characters[*str & UCHAR_MAX] = op;
  119.         Py_INCREF(op);
  120.     }
  121. #endif
  122.     return (PyObject *) op;
  123. }
  124.  
  125. PyObject *
  126. PyString_FromString(str)
  127.     const char *str;
  128. {
  129.     register unsigned int size = strlen(str);
  130.     register PyStringObject *op;
  131. #ifndef DONT_SHARE_SHORT_STRINGS
  132.     if (size == 0 && (op = nullstring) != NULL) {
  133. #ifdef COUNT_ALLOCS
  134.         null_strings++;
  135. #endif
  136.         Py_INCREF(op);
  137.         return (PyObject *)op;
  138.     }
  139.     if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  140. #ifdef COUNT_ALLOCS
  141.         one_strings++;
  142. #endif
  143.         Py_INCREF(op);
  144.         return (PyObject *)op;
  145.     }
  146. #endif /* DONT_SHARE_SHORT_STRINGS */
  147.     op = (PyStringObject *)
  148.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  149.     if (op == NULL)
  150.         return PyErr_NoMemory();
  151.     op->ob_type = &PyString_Type;
  152.     op->ob_size = size;
  153. #ifdef CACHE_HASH
  154.     op->ob_shash = -1;
  155. #endif
  156. #ifdef INTERN_STRINGS
  157.     op->ob_sinterned = NULL;
  158. #endif
  159.     _Py_NewReference(op);
  160.     strcpy(op->ob_sval, str);
  161. #ifndef DONT_SHARE_SHORT_STRINGS
  162.     if (size == 0) {
  163.         nullstring = op;
  164.         Py_INCREF(op);
  165.     } else if (size == 1) {
  166.         characters[*str & UCHAR_MAX] = op;
  167.         Py_INCREF(op);
  168.     }
  169. #endif
  170.     return (PyObject *) op;
  171. }
  172.  
  173. static void
  174. string_dealloc(op)
  175.     PyObject *op;
  176. {
  177.     PyMem_DEL(op);
  178. }
  179.  
  180. int
  181. PyString_Size(op)
  182.     register PyObject *op;
  183. {
  184.     if (!PyString_Check(op)) {
  185.         PyErr_BadInternalCall();
  186.         return -1;
  187.     }
  188.     return ((PyStringObject *)op) -> ob_size;
  189. }
  190.  
  191. /*const*/ char *
  192. PyString_AsString(op)
  193.     register PyObject *op;
  194. {
  195.     if (!PyString_Check(op)) {
  196.         PyErr_BadInternalCall();
  197.         return NULL;
  198.     }
  199.     return ((PyStringObject *)op) -> ob_sval;
  200. }
  201.  
  202. /* Methods */
  203.  
  204. static int
  205. string_print(op, fp, flags)
  206.     PyStringObject *op;
  207.     FILE *fp;
  208.     int flags;
  209. {
  210.     int i;
  211.     char c;
  212.     int quote;
  213.     /* XXX Ought to check for interrupts when writing long strings */
  214.     if (flags & Py_PRINT_RAW) {
  215.         fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
  216.         return 0;
  217.     }
  218.  
  219.     /* figure out which quote to use; single is prefered */
  220.     quote = '\'';
  221.     if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  222.         quote = '"';
  223.  
  224.     fputc(quote, fp);
  225.     for (i = 0; i < op->ob_size; i++) {
  226.         c = op->ob_sval[i];
  227.         if (c == quote || c == '\\')
  228.             fprintf(fp, "\\%c", c);
  229.         else if (c < ' ' || c >= 0177)
  230.             fprintf(fp, "\\%03o", c & 0377);
  231.         else
  232.             fputc(c, fp);
  233.     }
  234.     fputc(quote, fp);
  235.     return 0;
  236. }
  237.  
  238. static PyObject *
  239. string_repr(op)
  240.     register PyStringObject *op;
  241. {
  242.     /* XXX overflow? */
  243.     int newsize = 2 + 4 * op->ob_size * sizeof(char);
  244.     PyObject *v = PyString_FromStringAndSize((char *)NULL, newsize);
  245.     if (v == NULL) {
  246.         return NULL;
  247.     }
  248.     else {
  249.         register int i;
  250.         register char c;
  251.         register char *p;
  252.         int quote;
  253.  
  254.         /* figure out which quote to use; single is prefered */
  255.         quote = '\'';
  256.         if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  257.             quote = '"';
  258.  
  259.         p = ((PyStringObject *)v)->ob_sval;
  260.         *p++ = quote;
  261.         for (i = 0; i < op->ob_size; i++) {
  262.             c = op->ob_sval[i];
  263.             if (c == quote || c == '\\')
  264.                 *p++ = '\\', *p++ = c;
  265.             else if (c < ' ' || c >= 0177) {
  266.                 sprintf(p, "\\%03o", c & 0377);
  267.                 while (*p != '\0')
  268.                     p++;
  269.             }
  270.             else
  271.                 *p++ = c;
  272.         }
  273.         *p++ = quote;
  274.         *p = '\0';
  275.         _PyString_Resize(
  276.             &v, (int) (p - ((PyStringObject *)v)->ob_sval));
  277.         return v;
  278.     }
  279. }
  280.  
  281. static int
  282. string_length(a)
  283.     PyStringObject *a;
  284. {
  285.     return a->ob_size;
  286. }
  287.  
  288. static PyObject *
  289. string_concat(a, bb)
  290.     register PyStringObject *a;
  291.     register PyObject *bb;
  292. {
  293.     register unsigned int size;
  294.     register PyStringObject *op;
  295.     if (!PyString_Check(bb)) {
  296.         PyErr_BadArgument();
  297.         return NULL;
  298.     }
  299. #define b ((PyStringObject *)bb)
  300.     /* Optimize cases with empty left or right operand */
  301.     if (a->ob_size == 0) {
  302.         Py_INCREF(bb);
  303.         return bb;
  304.     }
  305.     if (b->ob_size == 0) {
  306.         Py_INCREF(a);
  307.         return (PyObject *)a;
  308.     }
  309.     size = a->ob_size + b->ob_size;
  310.     op = (PyStringObject *)
  311.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  312.     if (op == NULL)
  313.         return PyErr_NoMemory();
  314.     op->ob_type = &PyString_Type;
  315.     op->ob_size = size;
  316. #ifdef CACHE_HASH
  317.     op->ob_shash = -1;
  318. #endif
  319. #ifdef INTERN_STRINGS
  320.     op->ob_sinterned = NULL;
  321. #endif
  322.     _Py_NewReference(op);
  323.     memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size);
  324.     memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size);
  325.     op->ob_sval[size] = '\0';
  326.     return (PyObject *) op;
  327. #undef b
  328. }
  329.  
  330. static PyObject *
  331. string_repeat(a, n)
  332.     register PyStringObject *a;
  333.     register int n;
  334. {
  335.     register int i;
  336.     register int size;
  337.     register PyStringObject *op;
  338.     if (n < 0)
  339.         n = 0;
  340.     size = a->ob_size * n;
  341.     if (size == a->ob_size) {
  342.         Py_INCREF(a);
  343.         return (PyObject *)a;
  344.     }
  345.     op = (PyStringObject *)
  346.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  347.     if (op == NULL)
  348.         return PyErr_NoMemory();
  349.     op->ob_type = &PyString_Type;
  350.     op->ob_size = size;
  351. #ifdef CACHE_HASH
  352.     op->ob_shash = -1;
  353. #endif
  354. #ifdef INTERN_STRINGS
  355.     op->ob_sinterned = NULL;
  356. #endif
  357.     _Py_NewReference(op);
  358.     for (i = 0; i < size; i += a->ob_size)
  359.         memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size);
  360.     op->ob_sval[size] = '\0';
  361.     return (PyObject *) op;
  362. }
  363.  
  364. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  365.  
  366. static PyObject *
  367. string_slice(a, i, j)
  368.     register PyStringObject *a;
  369.     register int i, j; /* May be negative! */
  370. {
  371.     if (i < 0)
  372.         i = 0;
  373.     if (j < 0)
  374.         j = 0; /* Avoid signed/unsigned bug in next line */
  375.     if (j > a->ob_size)
  376.         j = a->ob_size;
  377.     if (i == 0 && j == a->ob_size) { /* It's the same as a */
  378.         Py_INCREF(a);
  379.         return (PyObject *)a;
  380.     }
  381.     if (j < i)
  382.         j = i;
  383.     return PyString_FromStringAndSize(a->ob_sval + i, (int) (j-i));
  384. }
  385.  
  386. static PyObject *
  387. string_item(a, i)
  388.     PyStringObject *a;
  389.     register int i;
  390. {
  391.     int c;
  392.     PyObject *v;
  393.     if (i < 0 || i >= a->ob_size) {
  394.         PyErr_SetString(PyExc_IndexError, "string index out of range");
  395.         return NULL;
  396.     }
  397.     c = a->ob_sval[i] & UCHAR_MAX;
  398.     v = (PyObject *) characters[c];
  399. #ifdef COUNT_ALLOCS
  400.     if (v != NULL)
  401.         one_strings++;
  402. #endif
  403.     if (v == NULL) {
  404.         v = PyString_FromStringAndSize((char *)NULL, 1);
  405.         if (v == NULL)
  406.             return NULL;
  407.         characters[c] = (PyStringObject *) v;
  408.         ((PyStringObject *)v)->ob_sval[0] = c;
  409.     }
  410.     Py_INCREF(v);
  411.     return v;
  412. }
  413.  
  414. static int
  415. string_compare(a, b)
  416.     PyStringObject *a, *b;
  417. {
  418.     int len_a = a->ob_size, len_b = b->ob_size;
  419.     int min_len = (len_a < len_b) ? len_a : len_b;
  420.     int cmp;
  421.     if (min_len > 0) {
  422.         cmp = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  423.         if (cmp == 0)
  424.             cmp = memcmp(a->ob_sval, b->ob_sval, min_len);
  425.         if (cmp != 0)
  426.             return cmp;
  427.     }
  428.     return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  429. }
  430.  
  431. static long
  432. string_hash(a)
  433.     PyStringObject *a;
  434. {
  435.     register int len;
  436.     register unsigned char *p;
  437.     register long x;
  438.  
  439. #ifdef CACHE_HASH
  440.     if (a->ob_shash != -1)
  441.         return a->ob_shash;
  442. #ifdef INTERN_STRINGS
  443.     if (a->ob_sinterned != NULL)
  444.         return (a->ob_shash =
  445.             ((PyStringObject *)(a->ob_sinterned))->ob_shash);
  446. #endif
  447. #endif
  448.     len = a->ob_size;
  449.     p = (unsigned char *) a->ob_sval;
  450.     x = *p << 7;
  451.     while (--len >= 0)
  452.         x = (1000003*x) ^ *p++;
  453.     x ^= a->ob_size;
  454.     if (x == -1)
  455.         x = -2;
  456. #ifdef CACHE_HASH
  457.     a->ob_shash = x;
  458. #endif
  459.     return x;
  460. }
  461.  
  462. static int
  463. string_buffer_getreadbuf(self, index, ptr)
  464.     PyStringObject *self;
  465.     int index;
  466.     const void **ptr;
  467. {
  468.     if ( index != 0 ) {
  469.         PyErr_SetString(PyExc_SystemError,
  470.                 "accessing non-existent string segment");
  471.         return -1;
  472.     }
  473.     *ptr = (void *)self->ob_sval;
  474.     return self->ob_size;
  475. }
  476.  
  477. static int
  478. string_buffer_getwritebuf(self, index, ptr)
  479.     PyStringObject *self;
  480.     int index;
  481.     const void **ptr;
  482. {
  483.     PyErr_SetString(PyExc_TypeError,
  484.             "Cannot use string as modifiable buffer");
  485.     return -1;
  486. }
  487.  
  488. static int
  489. string_buffer_getsegcount(self, lenp)
  490.     PyStringObject *self;
  491.     int *lenp;
  492. {
  493.     if ( lenp )
  494.         *lenp = self->ob_size;
  495.     return 1;
  496. }
  497.  
  498. static int
  499. string_buffer_getcharbuf(self, index, ptr)
  500.     PyStringObject *self;
  501.     int index;
  502.     const char **ptr;
  503. {
  504.     if ( index != 0 ) {
  505.         PyErr_SetString(PyExc_SystemError,
  506.                 "accessing non-existent string segment");
  507.         return -1;
  508.     }
  509.     *ptr = self->ob_sval;
  510.     return self->ob_size;
  511. }
  512.  
  513. static PySequenceMethods string_as_sequence = {
  514.     (inquiry)string_length, /*sq_length*/
  515.     (binaryfunc)string_concat, /*sq_concat*/
  516.     (intargfunc)string_repeat, /*sq_repeat*/
  517.     (intargfunc)string_item, /*sq_item*/
  518.     (intintargfunc)string_slice, /*sq_slice*/
  519.     0,        /*sq_ass_item*/
  520.     0,        /*sq_ass_slice*/
  521. };
  522.  
  523. static PyBufferProcs string_as_buffer = {
  524.     (getreadbufferproc)string_buffer_getreadbuf,
  525.     (getwritebufferproc)string_buffer_getwritebuf,
  526.     (getsegcountproc)string_buffer_getsegcount,
  527.     (getcharbufferproc)string_buffer_getcharbuf,
  528. };
  529.  
  530. PyTypeObject PyString_Type = {
  531.     PyObject_HEAD_INIT(&PyType_Type)
  532.     0,
  533.     "string",
  534.     sizeof(PyStringObject),
  535.     sizeof(char),
  536.     (destructor)string_dealloc, /*tp_dealloc*/
  537.     (printfunc)string_print, /*tp_print*/
  538.     0,        /*tp_getattr*/
  539.     0,        /*tp_setattr*/
  540.     (cmpfunc)string_compare, /*tp_compare*/
  541.     (reprfunc)string_repr, /*tp_repr*/
  542.     0,        /*tp_as_number*/
  543.     &string_as_sequence,    /*tp_as_sequence*/
  544.     0,        /*tp_as_mapping*/
  545.     (hashfunc)string_hash, /*tp_hash*/
  546.     0,        /*tp_call*/
  547.     0,        /*tp_str*/
  548.     0,        /*tp_getattro*/
  549.     0,        /*tp_setattro*/
  550.     &string_as_buffer,    /*tp_as_buffer*/
  551.     Py_TPFLAGS_DEFAULT,    /*tp_flags*/
  552.     0,        /*tp_doc*/
  553. };
  554.  
  555. void
  556. PyString_Concat(pv, w)
  557.     register PyObject **pv;
  558.     register PyObject *w;
  559. {
  560.     register PyObject *v;
  561.     if (*pv == NULL)
  562.         return;
  563.     if (w == NULL || !PyString_Check(*pv)) {
  564.         Py_DECREF(*pv);
  565.         *pv = NULL;
  566.         return;
  567.     }
  568.     v = string_concat((PyStringObject *) *pv, w);
  569.     Py_DECREF(*pv);
  570.     *pv = v;
  571. }
  572.  
  573. void
  574. PyString_ConcatAndDel(pv, w)
  575.     register PyObject **pv;
  576.     register PyObject *w;
  577. {
  578.     PyString_Concat(pv, w);
  579.     Py_XDECREF(w);
  580. }
  581.  
  582.  
  583. /* The following function breaks the notion that strings are immutable:
  584.    it changes the size of a string.  We get away with this only if there
  585.    is only one module referencing the object.  You can also think of it
  586.    as creating a new string object and destroying the old one, only
  587.    more efficiently.  In any case, don't use this if the string may
  588.    already be known to some other part of the code... */
  589.  
  590. int
  591. _PyString_Resize(pv, newsize)
  592.     PyObject **pv;
  593.     int newsize;
  594. {
  595.     register PyObject *v;
  596.     register PyStringObject *sv;
  597.     v = *pv;
  598.     if (!PyString_Check(v) || v->ob_refcnt != 1) {
  599.         *pv = 0;
  600.         Py_DECREF(v);
  601.         PyErr_BadInternalCall();
  602.         return -1;
  603.     }
  604.     /* XXX UNREF/NEWREF interface should be more symmetrical */
  605. #ifdef Py_REF_DEBUG
  606.     --_Py_RefTotal;
  607. #endif
  608.     _Py_ForgetReference(v);
  609.     *pv = (PyObject *)
  610.         realloc((char *)v,
  611.             sizeof(PyStringObject) + newsize * sizeof(char));
  612.     if (*pv == NULL) {
  613.         PyMem_DEL(v);
  614.         PyErr_NoMemory();
  615.         return -1;
  616.     }
  617.     _Py_NewReference(*pv);
  618.     sv = (PyStringObject *) *pv;
  619.     sv->ob_size = newsize;
  620.     sv->ob_sval[newsize] = '\0';
  621.     return 0;
  622. }
  623.  
  624. /* Helpers for formatstring */
  625.  
  626. static PyObject *
  627. getnextarg(args, arglen, p_argidx)
  628.     PyObject *args;
  629.     int arglen;
  630.     int *p_argidx;
  631. {
  632.     int argidx = *p_argidx;
  633.     if (argidx < arglen) {
  634.         (*p_argidx)++;
  635.         if (arglen < 0)
  636.             return args;
  637.         else
  638.             return PyTuple_GetItem(args, argidx);
  639.     }
  640.     PyErr_SetString(PyExc_TypeError,
  641.             "not enough arguments for format string");
  642.     return NULL;
  643. }
  644.  
  645. #define F_LJUST (1<<0)
  646. #define F_SIGN    (1<<1)
  647. #define F_BLANK (1<<2)
  648. #define F_ALT    (1<<3)
  649. #define F_ZERO    (1<<4)
  650.  
  651. static int
  652. formatfloat(buf, flags, prec, type, v)
  653.     char *buf;
  654.     int flags;
  655.     int prec;
  656.     int type;
  657.     PyObject *v;
  658. {
  659.     char fmt[20];
  660.     double x;
  661.     if (!PyArg_Parse(v, "d;float argument required", &x))
  662.         return -1;
  663.     if (prec < 0)
  664.         prec = 6;
  665.     if (prec > 50)
  666.         prec = 50; /* Arbitrary limitation */
  667.     if (type == 'f' && fabs(x)/1e25 >= 1e25)
  668.         type = 'g';
  669.     sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type);
  670.     sprintf(buf, fmt, x);
  671.     return strlen(buf);
  672. }
  673.  
  674. static int
  675. formatint(buf, flags, prec, type, v)
  676.     char *buf;
  677.     int flags;
  678.     int prec;
  679.     int type;
  680.     PyObject *v;
  681. {
  682.     char fmt[20];
  683.     long x;
  684.     if (!PyArg_Parse(v, "l;int argument required", &x))
  685.         return -1;
  686.     if (prec < 0)
  687.         prec = 1;
  688.     sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type);
  689.     sprintf(buf, fmt, x);
  690.     return strlen(buf);
  691. }
  692.  
  693. static int
  694. formatchar(buf, v)
  695.     char *buf;
  696.     PyObject *v;
  697. {
  698.     if (PyString_Check(v)) {
  699.         if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
  700.             return -1;
  701.     }
  702.     else {
  703.         if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
  704.             return -1;
  705.     }
  706.     buf[1] = '\0';
  707.     return 1;
  708. }
  709.  
  710.  
  711. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
  712.  
  713. PyObject *
  714. PyString_Format(format, args)
  715.     PyObject *format;
  716.     PyObject *args;
  717. {
  718.     char *fmt, *res;
  719.     int fmtcnt, rescnt, reslen, arglen, argidx;
  720.     int args_owned = 0;
  721.     PyObject *result;
  722.     PyObject *dict = NULL;
  723.     if (format == NULL || !PyString_Check(format) || args == NULL) {
  724.         PyErr_BadInternalCall();
  725.         return NULL;
  726.     }
  727.     fmt = PyString_AsString(format);
  728.     fmtcnt = PyString_Size(format);
  729.     reslen = rescnt = fmtcnt + 100;
  730.     result = PyString_FromStringAndSize((char *)NULL, reslen);
  731.     if (result == NULL)
  732.         return NULL;
  733.     res = PyString_AsString(result);
  734.     if (PyTuple_Check(args)) {
  735.         arglen = PyTuple_Size(args);
  736.         argidx = 0;
  737.     }
  738.     else {
  739.         arglen = -1;
  740.         argidx = -2;
  741.     }
  742.     if (args->ob_type->tp_as_mapping)
  743.         dict = args;
  744.     while (--fmtcnt >= 0) {
  745.         if (*fmt != '%') {
  746.             if (--rescnt < 0) {
  747.                 rescnt = fmtcnt + 100;
  748.                 reslen += rescnt;
  749.                 if (_PyString_Resize(&result, reslen) < 0)
  750.                     return NULL;
  751.                 res = PyString_AsString(result)
  752.                     + reslen - rescnt;
  753.                 --rescnt;
  754.             }
  755.             *res++ = *fmt++;
  756.         }
  757.         else {
  758.             /* Got a format specifier */
  759.             int flags = 0;
  760.             int width = -1;
  761.             int prec = -1;
  762.             int size = 0;
  763.             int c = '\0';
  764.             int fill;
  765.             PyObject *v = NULL;
  766.             PyObject *temp = NULL;
  767.             char *buf;
  768.             int sign;
  769.             int len;
  770.             char tmpbuf[120]; /* For format{float,int,char}() */
  771.             fmt++;
  772.             if (*fmt == '(') {
  773.                 char *keystart;
  774.                 int keylen;
  775.                 PyObject *key;
  776.                 int pcount = 1;
  777.  
  778.                 if (dict == NULL) {
  779.                     PyErr_SetString(PyExc_TypeError,
  780.                          "format requires a mapping"); 
  781.                     goto error;
  782.                 }
  783.                 ++fmt;
  784.                 --fmtcnt;
  785.                 keystart = fmt;
  786.                 /* Skip over balanced parentheses */
  787.                 while (pcount > 0 && --fmtcnt >= 0) {
  788.                     if (*fmt == ')')
  789.                         --pcount;
  790.                     else if (*fmt == '(')
  791.                         ++pcount;
  792.                     fmt++;
  793.                 }
  794.                 keylen = fmt - keystart - 1;
  795.                 if (fmtcnt < 0 || pcount > 0) {
  796.                     PyErr_SetString(PyExc_ValueError,
  797.                            "incomplete format key");
  798.                     goto error;
  799.                 }
  800.                 key = PyString_FromStringAndSize(keystart,
  801.                                  keylen);
  802.                 if (key == NULL)
  803.                     goto error;
  804.                 if (args_owned) {
  805.                     Py_DECREF(args);
  806.                     args_owned = 0;
  807.                 }
  808.                 args = PyObject_GetItem(dict, key);
  809.                 Py_DECREF(key);
  810.                 if (args == NULL) {
  811.                     goto error;
  812.                 }
  813.                 args_owned = 1;
  814.                 arglen = -1;
  815.                 argidx = -2;
  816.             }
  817.             while (--fmtcnt >= 0) {
  818.                 switch (c = *fmt++) {
  819.                 case '-': flags |= F_LJUST; continue;
  820.                 case '+': flags |= F_SIGN; continue;
  821.                 case ' ': flags |= F_BLANK; continue;
  822.                 case '#': flags |= F_ALT; continue;
  823.                 case '0': flags |= F_ZERO; continue;
  824.                 }
  825.                 break;
  826.             }
  827.             if (c == '*') {
  828.                 v = getnextarg(args, arglen, &argidx);
  829.                 if (v == NULL)
  830.                     goto error;
  831.                 if (!PyInt_Check(v)) {
  832.                     PyErr_SetString(PyExc_TypeError,
  833.                             "* wants int");
  834.                     goto error;
  835.                 }
  836.                 width = PyInt_AsLong(v);
  837.                 if (width < 0)
  838.                     width = 0;
  839.                 if (--fmtcnt >= 0)
  840.                     c = *fmt++;
  841.             }
  842.             else if (c >= 0 && isdigit(c)) {
  843.                 width = c - '0';
  844.                 while (--fmtcnt >= 0) {
  845.                     c = Py_CHARMASK(*fmt++);
  846.                     if (!isdigit(c))
  847.                         break;
  848.                     if ((width*10) / 10 != width) {
  849.                         PyErr_SetString(
  850.                             PyExc_ValueError,
  851.                             "width too big");
  852.                         goto error;
  853.                     }
  854.                     width = width*10 + (c - '0');
  855.                 }
  856.             }
  857.             if (c == '.') {
  858.                 prec = 0;
  859.                 if (--fmtcnt >= 0)
  860.                     c = *fmt++;
  861.                 if (c == '*') {
  862.                     v = getnextarg(args, arglen, &argidx);
  863.                     if (v == NULL)
  864.                         goto error;
  865.                     if (!PyInt_Check(v)) {
  866.                         PyErr_SetString(
  867.                             PyExc_TypeError,
  868.                             "* wants int");
  869.                         goto error;
  870.                     }
  871.                     prec = PyInt_AsLong(v);
  872.                     if (prec < 0)
  873.                         prec = 0;
  874.                     if (--fmtcnt >= 0)
  875.                         c = *fmt++;
  876.                 }
  877.                 else if (c >= 0 && isdigit(c)) {
  878.                     prec = c - '0';
  879.                     while (--fmtcnt >= 0) {
  880.                         c = Py_CHARMASK(*fmt++);
  881.                         if (!isdigit(c))
  882.                             break;
  883.                         if ((prec*10) / 10 != prec) {
  884.                             PyErr_SetString(
  885.                                 PyExc_ValueError,
  886.                                 "prec too big");
  887.                             goto error;
  888.                         }
  889.                         prec = prec*10 + (c - '0');
  890.                     }
  891.                 }
  892.             } /* prec */
  893.             if (fmtcnt >= 0) {
  894.                 if (c == 'h' || c == 'l' || c == 'L') {
  895.                     size = c;
  896.                     if (--fmtcnt >= 0)
  897.                         c = *fmt++;
  898.                 }
  899.             }
  900.             if (fmtcnt < 0) {
  901.                 PyErr_SetString(PyExc_ValueError,
  902.                         "incomplete format");
  903.                 goto error;
  904.             }
  905.             if (c != '%') {
  906.                 v = getnextarg(args, arglen, &argidx);
  907.                 if (v == NULL)
  908.                     goto error;
  909.             }
  910.             sign = 0;
  911.             fill = ' ';
  912.             switch (c) {
  913.             case '%':
  914.                 buf = "%";
  915.                 len = 1;
  916.                 break;
  917.             case 's':
  918.                 temp = PyObject_Str(v);
  919.                 if (temp == NULL)
  920.                     goto error;
  921.                 if (!PyString_Check(temp)) {
  922.                     PyErr_SetString(PyExc_TypeError,
  923.                       "%s argument has non-string str()");
  924.                     goto error;
  925.                 }
  926.                 buf = PyString_AsString(temp);
  927.                 len = PyString_Size(temp);
  928.                 if (prec >= 0 && len > prec)
  929.                     len = prec;
  930.                 break;
  931.             case 'i':
  932.             case 'd':
  933.             case 'u':
  934.             case 'o':
  935.             case 'x':
  936.             case 'X':
  937.                 if (c == 'i')
  938.                     c = 'd';
  939.                 buf = tmpbuf;
  940.                 len = formatint(buf, flags, prec, c, v);
  941.                 if (len < 0)
  942.                     goto error;
  943.                 sign = (c == 'd');
  944.                 if (flags&F_ZERO) {
  945.                     fill = '0';
  946.                     if ((flags&F_ALT) &&
  947.                         (c == 'x' || c == 'X') &&
  948.                         buf[0] == '0' && buf[1] == c) {
  949.                         *res++ = *buf++;
  950.                         *res++ = *buf++;
  951.                         rescnt -= 2;
  952.                         len -= 2;
  953.                         width -= 2;
  954.                         if (width < 0)
  955.                             width = 0;
  956.                     }
  957.                 }
  958.                 break;
  959.             case 'e':
  960.             case 'E':
  961.             case 'f':
  962.             case 'g':
  963.             case 'G':
  964.                 buf = tmpbuf;
  965.                 len = formatfloat(buf, flags, prec, c, v);
  966.                 if (len < 0)
  967.                     goto error;
  968.                 sign = 1;
  969.                 if (flags&F_ZERO)
  970.                     fill = '0';
  971.                 break;
  972.             case 'c':
  973.                 buf = tmpbuf;
  974.                 len = formatchar(buf, v);
  975.                 if (len < 0)
  976.                     goto error;
  977.                 break;
  978.             default:
  979.                 PyErr_Format(PyExc_ValueError,
  980.                 "unsupported format character '%c' (0x%x)",
  981.                     c, c);
  982.                 goto error;
  983.             }
  984.             if (sign) {
  985.                 if (*buf == '-' || *buf == '+') {
  986.                     sign = *buf++;
  987.                     len--;
  988.                 }
  989.                 else if (flags & F_SIGN)
  990.                     sign = '+';
  991.                 else if (flags & F_BLANK)
  992.                     sign = ' ';
  993.                 else
  994.                     sign = '\0';
  995.             }
  996.             if (width < len)
  997.                 width = len;
  998.             if (rescnt < width + (sign != '\0')) {
  999.                 reslen -= rescnt;
  1000.                 rescnt = width + fmtcnt + 100;
  1001.                 reslen += rescnt;
  1002.                 if (_PyString_Resize(&result, reslen) < 0)
  1003.                     return NULL;
  1004.                 res = PyString_AsString(result)
  1005.                     + reslen - rescnt;
  1006.             }
  1007.             if (sign) {
  1008.                 if (fill != ' ')
  1009.                     *res++ = sign;
  1010.                 rescnt--;
  1011.                 if (width > len)
  1012.                     width--;
  1013.             }
  1014.             if (width > len && !(flags&F_LJUST)) {
  1015.                 do {
  1016.                     --rescnt;
  1017.                     *res++ = fill;
  1018.                 } while (--width > len);
  1019.             }
  1020.             if (sign && fill == ' ')
  1021.                 *res++ = sign;
  1022.             memcpy(res, buf, len);
  1023.             res += len;
  1024.             rescnt -= len;
  1025.             while (--width >= len) {
  1026.                 --rescnt;
  1027.                 *res++ = ' ';
  1028.             }
  1029.                         if (dict && (argidx < arglen) && c != '%') {
  1030.                                 PyErr_SetString(PyExc_TypeError,
  1031.                                            "not all arguments converted");
  1032.                                 goto error;
  1033.                         }
  1034.             Py_XDECREF(temp);
  1035.         } /* '%' */
  1036.     } /* until end */
  1037.     if (argidx < arglen && !dict) {
  1038.         PyErr_SetString(PyExc_TypeError,
  1039.                 "not all arguments converted");
  1040.         goto error;
  1041.     }
  1042.     if (args_owned) {
  1043.         Py_DECREF(args);
  1044.     }
  1045.     _PyString_Resize(&result, reslen - rescnt);
  1046.     return result;
  1047.  error:
  1048.     Py_DECREF(result);
  1049.     if (args_owned) {
  1050.         Py_DECREF(args);
  1051.     }
  1052.     return NULL;
  1053. }
  1054.  
  1055.  
  1056. #ifdef INTERN_STRINGS
  1057.  
  1058. static PyObject *interned;
  1059.  
  1060. void
  1061. PyString_InternInPlace(p)
  1062.     PyObject **p;
  1063. {
  1064.     register PyStringObject *s = (PyStringObject *)(*p);
  1065.     PyObject *t;
  1066.     if (s == NULL || !PyString_Check(s))
  1067.         Py_FatalError("PyString_InternInPlace: strings only please!");
  1068.     if ((t = s->ob_sinterned) != NULL) {
  1069.         if (t == (PyObject *)s)
  1070.             return;
  1071.         Py_INCREF(t);
  1072.         *p = t;
  1073.         Py_DECREF(s);
  1074.         return;
  1075.     }
  1076.     if (interned == NULL) {
  1077.         interned = PyDict_New();
  1078.         if (interned == NULL)
  1079.             return;
  1080.     }
  1081.     if ((t = PyDict_GetItem(interned, (PyObject *)s)) != NULL) {
  1082.         Py_INCREF(t);
  1083.         *p = s->ob_sinterned = t;
  1084.         Py_DECREF(s);
  1085.         return;
  1086.     }
  1087.     t = (PyObject *)s;
  1088.     if (PyDict_SetItem(interned, t, t) == 0) {
  1089.         s->ob_sinterned = t;
  1090.         return;
  1091.     }
  1092.     PyErr_Clear();
  1093. }
  1094.  
  1095.  
  1096. PyObject *
  1097. PyString_InternFromString(cp)
  1098.     const char *cp;
  1099. {
  1100.     PyObject *s = PyString_FromString(cp);
  1101.     if (s == NULL)
  1102.         return NULL;
  1103.     PyString_InternInPlace(&s);
  1104.     return s;
  1105. }
  1106.  
  1107. #endif
  1108.  
  1109. void
  1110. PyString_Fini()
  1111. {
  1112.     int i;
  1113.     for (i = 0; i < UCHAR_MAX + 1; i++) {
  1114.         Py_XDECREF(characters[i]);
  1115.         characters[i] = NULL;
  1116.     }
  1117. #ifndef DONT_SHARE_SHORT_STRINGS
  1118.     Py_XDECREF(nullstring);
  1119.     nullstring = NULL;
  1120. #endif
  1121. #ifdef INTERN_STRINGS
  1122.     if (interned) {
  1123.         int pos, changed;
  1124.         PyObject *key, *value;
  1125.         do {
  1126.             changed = 0;
  1127.             pos = 0;
  1128.             while (PyDict_Next(interned, &pos, &key, &value)) {
  1129.                 if (key->ob_refcnt == 2 && key == value) {
  1130.                     PyDict_DelItem(interned, key);
  1131.                     changed = 1;
  1132.                 }
  1133.             }
  1134.         } while (changed);
  1135.     }
  1136. #endif
  1137. }
  1138.